from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def levelOrder(root: TreeNode):
    if not root:
        return []
    
    result = []
    queue = deque([root])
    
    while queue:
        level_size = len(queue)
        current_level = []
        
        for _ in range(level_size):
            node = queue.popleft()
            current_level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        
        result.append(current_level)
        print("level res=", result)

    print("final res=", result)
    return result

def test_levelOrder():
    # 测试示例 1
    root = TreeNode(3)
    root.left = TreeNode(9)
    root.right = TreeNode(20)
    root.right.left = TreeNode(15)
    root.right.right = TreeNode(7)
    assert levelOrder(root) == [[3], [9, 20], [15, 7]], "测试示例 1 失败"
    
    # 测试示例 2: 只有一个节点的树
    root = TreeNode(1)
    assert levelOrder(root) == [[1]], "测试示例 2 失败"
    
    # 测试示例 3: 空树
    root = None
    assert levelOrder(root) == [], "测试示例 3 失败"
    
    # 测试示例 4: 完全二叉树
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)
    root.right.left = TreeNode(6)
    root.right.right = TreeNode(7)
    assert levelOrder(root) == [[1], [2, 3], [4, 5, 6, 7]], "测试示例 4 失败"
    
    print("所有测试用例通过！")

# 运行测试
test_levelOrder()
